package com.hmall.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.clients.FeginClient;
import com.hmall.common.clients.UserClient;
import com.hmall.common.dto.Address;
import com.hmall.common.dto.Item;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderLogisticsMapper;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.pojo.RequestParams;
import com.hmall.order.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    OrderLogisticsMapper orderLogisticsMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    FeginClient feginClient;

    @Autowired
    UserClient userClient;
    @Override
    public Long creatOrder(RequestParams requestParams) {

        Long itemId = requestParams.getItemId();
        String itemById = feginClient.findItemById(itemId);
        Item item = JSON.parseObject(itemById, Item.class);


        Long addressId = requestParams.getAddressId();
        Address address = userClient.findAddressById(addressId);

        Long userId = address.getUserId();


        Integer itemNum = requestParams.getNum();
        Long price = item.getPrice();

        Long total =itemNum* (price*100);

        Integer paymentType = requestParams.getPaymentType();
        Order order = new Order();
        order.setTotalFee(total);
        order.setStatus(1); //1 、表示未支付
        order.setUserId(userId);
        order.setPaymentType(paymentType);


        boolean n1 = this.save(order);
        if (n1){
            System.out.println("订单存储成功================================>");
            System.err.println("订单id是：==================>" + order.getId());
        }

        Long orderId = orderMapper.queryOrderIdByOrderByTime();

        OrderDetail orderDetail = new OrderDetail(item);
        orderDetail.setOrderId(orderId);
        orderDetail.setNum(itemNum);
        int insert = orderDetailMapper.insert(orderDetail);
        OrderLogistics orderLogistics = new OrderLogistics(address);
        orderLogistics.setOrderId(orderId);
        int insert1 = orderLogisticsMapper.insert(orderLogistics);

        //调用item-service的减库存接口
        boolean n2 = feginClient.downItemStockById(itemId,itemNum);

        if (n1 && n2 && insert > 0 && insert1 > 0){
            System.err.println("order服务运行正常===========================>");

            System.out.println("订单id是=====>" + orderId);

            return orderId;
        }

        return null;
    }
}

